package mk.company.fin.model;

import java.math.BigDecimal;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

import mk.company.fin.FinConstants;

@Entity
@Table(name = FinConstants.Tables.YEAR)
public class Year extends Model {

	private static final long serialVersionUID = 8111555097515453205L;

	// persistent
	private Long year;
	private Organization organization;
	private List<Nalog> nalogs;
	
	// transient
	private BigDecimal dolzi;
	private BigDecimal pobaruva;
	private BigDecimal saldo;
	
	
	@Id
	@Column(name = "year")
	public Long getYear() {
		return year;
	}

	public void setYear(Long year) {
		this.year = year;
	}
	
	@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
	@JoinColumn(name = "id_organization", nullable = false)
	public Organization getOrganization() {
		return organization;
	}

	public void setOrganization(Organization organization) {
		this.organization = organization;
	}

	@OneToMany(mappedBy = "year", orphanRemoval = true, fetch = FetchType.LAZY)
	public List<Nalog> getNalogs() {
		return nalogs;
	}

	public void setNalogs(List<Nalog> nalogs) {
		this.nalogs = nalogs;
	}
	
	
	/**
	 * Calculates the "dolzi", "pobaruva" and "saldo" parts.
	 */
	public void calculateTotals() {
		// init
		dolzi = BigDecimal.ZERO;
		dolzi.setScale(FinConstants.Application.NUMBER_SCALE);
		pobaruva = BigDecimal.ZERO;
		pobaruva.setScale(FinConstants.Application.NUMBER_SCALE);
		
		// calculate
		for (Nalog nalog : getNalogs()) {
			nalog.calculateTotals();
			dolzi.add(nalog.getDolzi());
			pobaruva.add(nalog.getPobaruva());
		}
		
		// saldo
		saldo = dolzi.subtract(pobaruva);
	}

	
	@Transient
	public BigDecimal getDolzi() {
		return dolzi;
	}
	
	@Deprecated
	public void setDolzi(BigDecimal dolzi) {
		throw new UnsupportedOperationException("The field dolzi is dynamic! Use the calculateTotals mehtod!");
	}
	
	@Transient
	public BigDecimal getPobaruva() {
		return pobaruva;
	}
	
	@Deprecated
	public void setPobaruva(BigDecimal pobaruva) {
		throw new UnsupportedOperationException("The field pobaruva is dynamic! Use the calculateTotals mehtod!");
	}
	
	@Transient
	public BigDecimal getSaldo() {
		return saldo;
	}
	
	@Deprecated
	public void setSaldo(BigDecimal saldo) {
		throw new UnsupportedOperationException("The field saldo is dynamic! Use the calculateTotals mehtod!");
	}

}
